<template>
  <div>
    <a-transfer
      :data-source="mockData"
      :target-keys="targetKeys"
      :disabled="disabled"
      :show-search="showSearch"
      :filter-option="(inputValue, item) => item.code.indexOf(inputValue) !== -1"
      :show-select-all="false"
      :titles="titles"
      @change="onChange"
    >
      <template
        #children="{
          direction,
          filteredItems,
          selectedKeys,
          disabled: listDisabled,
          onItemSelectAll,
          onItemSelect,
        }"
      >
        <a-table
          :row-selection="
            getRowSelection({
              disabled: listDisabled,
              selectedKeys,
              onItemSelectAll,
              onItemSelect,
            })
          "
          :columns="direction === 'left' ? leftColumns : rightColumns"
          :data-source="filteredItems"
          size="small"
          :style="{ pointerEvents: listDisabled ? 'none' : null }"
          :custom-row="
            ({ key, disabled: itemDisabled }) => ({
              onClick: () => {
                if (itemDisabled || listDisabled) return;
                onItemSelect(key, !selectedKeys.includes(key));
              },
            })
          "
        />
      </template>
    </a-transfer>
    <!--    <a-switch
          un-checked-children="disabled"
          checked-children="disabled"
          v-model:checked="disabled"
          style="margin-top: 16px"
        />
        <a-switch
          un-checked-children="showSearch"
          checked-children="showSearch"
          v-model:checked="showSearch"
          style="margin-top: 16px"
        />-->
  </div>
</template>
<script lang="ts">
  import { difference } from 'lodash-es';
  import { defineComponent, nextTick, onMounted, reactive, ref,toRefs,unref } from 'vue';
  import {listAll as listperson} from "@/views/baseinfo/person/SsPerson.api";
  import {adds, deleteBy, list, listGroupPerson} from "@/views/baseinfo/persongroup/SsPersonGroup.api";
  import {saveOrUpdate} from "@/views/baseinfo/persongroup/SsPersonGroup.api";

  interface MockData {
    key: string;
    code: string;
    name: string;
    disabled: boolean;
  }
  type tableColumn = Record<string, string>;
  let mockData: MockData[] = reactive([]);
/*  for (let i = 0; i < 20; i++) {
    mockData.push({
      key: i.toString(),
      title: `content${i + 1}`,
      description: `description of content${i + 1}`,
      disabled: false,//i % 4 === 0,
    });
  }*/




  const originTargetKeys =reactive([]);;//mockData.map(item => item.key);//.filter(item => +item.key % 3 > 1).map(item => item.key);

  const leftTableColumns = [
    {
      dataIndex: 'code',
      title: '学/工号',
    },
    {
      dataIndex: 'name',
      title: '姓名',
    },
  ];
  const rightTableColumns = [
    {
      dataIndex: 'code',
      title: '学/工号',
    },
    {
      dataIndex: 'name',
      title: '姓名',
    },
  ];
  const titles = reactive([]);

  const gname = ref();


  export default defineComponent({
    props:{
      targetGroup:String,
      groupName:String,
      departmentId:String,
    },
    setup(props) {
      const targetKeys = ref<string[]>(originTargetKeys);
      const disabled = ref<boolean>(false);
      const showSearch = ref<boolean>(true);
      const leftColumns = ref<tableColumn[]>(leftTableColumns);
      const rightColumns = ref<tableColumn[]>(rightTableColumns);
      const {targetGroup,groupName,departmentId} = toRefs(props);
      console.log(targetGroup);
      console.log(props)
      console.log(groupName.value)
      console.log(departmentId.value)


      const onChange = (nextTargetKeys: string[]) => {

          nextTick(async () => {

            console.log(nextTargetKeys);
            console.log(targetKeys.value);
            console.log(difference(nextTargetKeys, targetKeys.value))
            console.log(difference(targetKeys.value, nextTargetKeys))


            let add = difference(nextTargetKeys, targetKeys.value);
            let remove = difference(targetKeys.value, nextTargetKeys);
            if (add.length > 0) {

              let ids = "";
              for (let i= 0;i<add.length;i++) {
                ids =ids+ add[i] + ","
              }
              console.log(add)
              console.log(ids)
              let params = {};
              params.personId = ids;
              params.groupId = targetGroup.value;
              console.log(params)
              adds(params);

            }
            if (remove.length > 0) {
              let params = {};
              let ids = "";
              for (let i in remove) {
                ids = ids+remove[i] + ","
              }
              params.personId = ids;
              params.groupId = targetGroup.value;
              deleteBy(params, null);
            }

            targetKeys.value = nextTargetKeys;
          });
      };

      const groupperson = async ()=>{
        let params={};
        console.log(targetGroup.value)
        params.groupId=targetGroup.value;
        console.log(params);
          let res = await listGroupPerson(params);
          let len = res.length;
          console.log(res)
          if(len>0) {
            for (let i = 0; i<res.length; i++) {
              mockData.push({
                key: res[i].id,
                code: res[i].code,
                name: res[i].name,
                disabled: false,//i % 4 === 0,
              });
            }
            let temp = res.map(item => item.id);
            console.log(temp);
            return temp;
          }
          else
            return [];
      };
      const filteredItems1 =  async ()=>{
        let params = {};
        params.groupId=targetGroup.value;
        params.departmentId = departmentId.value;
        let res = await listperson(params);
        console.log(res);
        const mockData1: MockData[] = [];
        if(!res){
          return mockData1;
        }

        for (let i = 0; i<res.length; i++) {
          mockData1.push({
            key: res[i].id,
            code: res[i].code,
            name: res[i].name,
            disabled: false,//i % 4 === 0,
          });
        }
        return mockData1;
      }


      const getRowSelection = ({
                                 disabled,
                                 selectedKeys,
                                 onItemSelectAll,
                                 onItemSelect,
                               }: Record<string, any>) => {
        return {
          getCheckboxProps: (item: Record<string, string | boolean>) => ({
            disabled: disabled || item.disabled,
          }),
          onSelectAll(selected: boolean, selectedRows: Record<string, string | boolean>[]) {
            const treeSelectedKeys = selectedRows
              .filter(item => !item.disabled)
              .map(({ key }) => key);
            const diffKeys = selected
              ? difference(treeSelectedKeys, selectedKeys)
              : difference(selectedKeys, treeSelectedKeys);
            console.log(selected)
            //if(selected){
            //  onItemSelectAll(treeSelectedKeys, selected);
            // }else
            if(selected){
              onItemSelectAll(diffKeys, selected);
            }else{
              onItemSelectAll([], selected);
            }


          },
          onSelect({ key }: Record<string, string>, selected: boolean) {
            onItemSelect(key, selected);
          },
          selectedRowKeys: selectedKeys,
        };
      };
      onMounted(async () => {
        nextTick(async () => {
          setTimeout(async ()=>{
            console.log(targetGroup)
            let res = await filteredItems1();
            mockData.splice(0,mockData.length);
            mockData.push(...res);
            console.log(targetGroup);
            let res1 = await groupperson();
            originTargetKeys.splice(0,originTargetKeys.length);
            originTargetKeys.push(...res1);

            gname.value = "("+groupName.value+"分组)";
            titles.splice(0,titles.length);
            titles.push("");
            titles.push(groupName.value);
          },100)



        });
      });
      return {
        titles,
        mockData,
        targetKeys,
        disabled,
        showSearch,
        leftColumns,
        rightColumns,
        onChange,
        getRowSelection,
      };
    },
  });
</script>

